import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Button, Block} from "@tarojs/components"
import "../profile/profile.scss"
import {AtForm, AtInput, AtButton, AtModalHeader, AtModalContent, AtModalAction, AtModal} from "taro-ui"
import WxValidate from '../../utils/wx-validate'
import { user } from "../../utils/user.service"
import {SELLER_PROMOTION_CODE_CHECK, SELLER_PROMOTION_CODE_BIND} from "../../constants/api"
import { SellerInfo, PlatformSet } from '../../utils/server.interface'
import { platform } from '../../utils/platform-settting.service'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {newHttp} from "../../utils/request";
import {GetRequest,vcmonitor} from "../../utils/tools";
interface stateType {
  formData: formData;
  errList: {
    is_show_seller_phone?: boolean;
    seller_real_name: boolean;
    poster_name?: boolean;
    seller_phone?: boolean;
    slogan?: boolean;
    company?: boolean;
    area?: boolean;
    address?: boolean;
    wx_no?:boolean;
  };
  sellerInfo: SellerInfo | false;
  submiting: boolean;
  isLogin: boolean;
  rate: number;
  checkInfo: any
  modalShow: boolean
}

interface updateInfo {
  id: number;
  poster_name: string;
  seller_real_name: string;
  seller_phone: string;
  slogan: string;
  company: string;
  area: string;
  address: string;
  delivery_province: string;
  delivery_city: string;
  delivery_area: string;
  is_show_seller_phone: number;
  wx_no?:string;
  rate?: number;
}
interface formData {
  is_show_seller_phone: boolean;
  seller_real_name: string;
  poster_name: string;
  seller_phone: string;
  slogan: string;
  company: string;
  area: string[];
  wx_no?:string;
  address: string;
}
export default class Profile extends Component {
  state:stateType = {
    isLogin: false,
    formData: {
      seller_real_name: '',
      seller_phone: '',
    },
    errList: {
      seller_real_name: false,
      seller_phone: false
    },
    sellerInfo: false,
    submiting: false,
    rate: 0,
    checkInfo: [],
    modalShow: false
  }
  rules = {
    seller_real_name: {
      required: true,
    },
    seller_phone: {
      required: true,
      tel: true
    }
  }
  message = {
    seller_real_name: {
      required: "姓名不能为空",
    },
    seller_phone: {
      required: "手机号码不能为空",
      tel: "手机号码不正确"
    }
  }
  platformSet: PlatformSet | false = false
  async UNSAFE_componentWillMount() {
    if(process.env.TARO_ENV==='h5'){
      await h5Wx.getConfig()
    }
  }
  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    this.setState({ isLogin })
    if(!isLogin){
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(async () => {
        clearTimeout(timer)
        const userData = await user.getUserData()
      }, 1000)
      return
    } else {
      const code = Taro.getCurrentInstance().router.params.scene
      const checkInfo = await newHttp.catchPost(SELLER_PROMOTION_CODE_CHECK,{ticket:code}, true)
      if(checkInfo.msg){
        Taro.showToast({
          title: checkInfo.msg,
          duration: 3000,
          icon: 'none',
        })
      }
      const { formData } = this.state
      formData['ticket'] = code
      this.setState({checkInfo, formData})
      // 需要绑定
      if(checkInfo.is_need_bind == 1){
        if(checkInfo.is_seller == 1){
          let { formData } =this.state
          formData.seller_real_name = checkInfo.seller_real_name
          formData.seller_phone = checkInfo.seller_phone
          this.setState({formData})
        } else {
          // 用户身份

        }
      } else {
        if(checkInfo.show_message){
          Taro.showToast({
            duration: 3000,
            title: checkInfo.show_message,
            icon: 'none',
          })
        }
        if(checkInfo.jump == 'index'){
          const timer = setTimeout(async () => {
            clearTimeout(timer)
            Taro.switchTab({ url: '/pages/index/index' })
          }, 1500)
        }

      }
    }
    this.platformSet = await platform.getSetting()
  }
  inputChange(type, value) {
    const oldData = this.state.formData
    oldData[type] = value
    this.setState({formData: oldData})
  }
  toIndex(){
    Taro.switchTab({ url: '/pages/index/index' })
  }
  async submitForm() {
    this.setState({ submiting: true }, async ()=> {
      const validate = new WxValidate(this.rules, this.message)
      if(!validate.checkForm(this.state.formData)){
        const oldData = this.state.errList
        if(validate && validate.errorList && validate.errorList[0].param){
          oldData[validate.errorList[0].param] = true
          Taro.showToast({
            title: validate.errorList[0].msg,
            icon: 'none'
          })
        }
        this.setState({ errList: oldData, submiting: false })
        return false;
      }
      const data:updateInfo = {
        ...this.state.formData
      }

      if(this.state.sellerInfo && this.platformSet){
        if(this.state.sellerInfo.type === 2 && this.platformSet.platformSellerType === 0) {
          data.rate = this.state.rate || 0
        }
      }
      const ret = await newHttp.catchPost(SELLER_PROMOTION_CODE_BIND, data)
      if(ret){
        this.setState({ submiting: false ,modalShow:false})
        if(ret.msg){
          Taro.showToast({
            title: ret.msg,
            duration: 3000,
            icon: 'none',
          })
        }
        if(ret.jump == 'index'){
          const timer = setTimeout(async () => {
            clearTimeout(timer)
            Taro.switchTab({ url: '/pages/my/index/index' })
          }, 1500)
        }
      } else {
        this.setState({ submiting: false ,modalShow:false})
      }
    })
  }
  onChange = e => {
    let { value } = e.detail;
    //console.log(e.detail)
    this.getAddressName(value);
  };
  handleCancel() {
    this.setState({modalShow: false, submiting: false})
  }
  handleClose(){
    this.setState({modalShow: false, submiting: false})
  }
  handleConfirm(){
    this.setState({ submiting: true }, async ()=> {
      const validate = new WxValidate(this.rules, this.message)
      if(!validate.checkForm(this.state.formData)){
        const oldData = this.state.errList
        if(validate && validate.errorList && validate.errorList[0].param){
          oldData[validate.errorList[0].param] = true
          Taro.showToast({
            title: validate.errorList[0].msg,
            icon: 'none'
          })
        }
        this.setState({ errList: oldData, submiting: false })
        return false;
      }
      this.setState({modalShow:true})
    })
  }
  render() {
    const {checkInfo,modalShow,formData, errList, submiting, isLogin} = this.state
    return(
      <View className="profile-root">
        { isLogin && checkInfo.jump === '' && <Block>
          <GzhAuth />
          <View className='head'>
            <View className="title">推广码注册</View>
            <View className="tips">请填写以下内容</View>
          </View>
          <AtForm>
            <AtInput error={errList.seller_real_name} maxLength={15} onChange={this.inputChange.bind(this, 'seller_real_name')} name="seller_real_name" title="姓名" value={formData.seller_real_name && formData.seller_real_name!='null'?formData.seller_real_name:''}  placeholder="请填写姓名"></AtInput>
            <AtInput error={errList.seller_phone} onChange={this.inputChange.bind(this, 'seller_phone')} name="seller_phone" title="手机号码" value={formData.seller_phone} placeholder="请填写手机号（无需+86）">
            </AtInput>
          </AtForm>
          <View style={'padding: 50rpx 40rpx 50rpx;'} className="btn"><AtButton disabled={submiting} loading={submiting} type="primary" formType='submit' onClick={this.handleConfirm.bind(this)}>绑定</AtButton></View>
          {/*<View className="btn"><AtButton disabled={submiting} loading={submiting} type="primary"  onClick={this.toIndex.bind(this)}>去首页</AtButton></View>*/}
          <View onClick={this.toIndex.bind(this)} className='promotion-home'>去首页</View>
          <View className="ios"></View>
        </Block> }
        <AtModal isOpened={modalShow} onClose={this.handleCancel.bind(this)}>
          <AtModalHeader>提示</AtModalHeader>
          <AtModalContent>
            <View className='modal-tips'> 是否绑定?</View>

          </AtModalContent>
          <AtModalAction>
            <Button onClick={this.handleClose.bind(this)}>否</Button>
            <Button onClick={this.submitForm.bind(this)}>是</Button>
          </AtModalAction>
        </AtModal>
      </View>
    )
  }
}
